﻿using System.Text;
using System.Linq;

namespace WebStickyNotes.Helpers
{
    public static class MegaSelectListHelper
    {
        private const string SelectElement = "<select id=\"{0}\" name=\"{1}\" class=\"mega\">{2}</select>";
        private const string OptionElement = "<option value=\"{0}\"{1}>{2}</option>";
        private const string OptionGroupStart = "<optgroup label=\"{0}\">";
        private const string OptionGroupEnd = "</optgroup>";
        private const string SelectedItem = " selected=\"true\"";

        public static string DropDownList(string name, MegaSelectList megaSelectList)
        {
            var stringBuilder = new StringBuilder();

            var groupName = string.Empty;
            var groupOpen = false;

            foreach (var megaSelectListItem in megaSelectList.Items)
            {
                if (megaSelectListItem != null)
                {
                    // Deals With Option Groups
                    if (megaSelectListItem.GroupName != groupName)
                    {
                        groupName = megaSelectListItem.GroupName;

                        if (groupOpen)
                        {
                            stringBuilder.Append(OptionGroupEnd);
                        }

                        stringBuilder.AppendFormat(OptionGroupStart, groupName);
                        groupOpen = true;
                    }

                    // Deals With Options
                    stringBuilder.AppendFormat(
                        OptionElement,
                        megaSelectListItem.Value,
                        megaSelectListItem.Selected ? SelectedItem : string.Empty,
                        megaSelectListItem.Text);
                }
            }

            if (groupOpen)
            {
                stringBuilder.Append(OptionGroupEnd);
            }

            var id = name.Replace('.', '_');

            return string.Format(SelectElement, id, name, stringBuilder);
        }
    }
}